package com.lx.wxdemo.controller;

/**
 * @Description TODO
 * @Author lx
 * @Date 2021/1/5 11:24
 **/

import com.lx.wxdemo.entity.User;
import com.lx.wxdemo.service.WxService;
import com.lx.wxdemo.utils.HttpUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginHandler {
    @Autowired
    private WxService wxService;

    @Value("${APP_ID}")
    private String appID ;

    @Value("${secret}")
    private String appSecret = "";

    @PostMapping("/tologin")
    public Map userLogin(@RequestParam("code") String code) throws IOException {
        System.out.println("进入login-controller");

        Map map = new HashMap();


        String result = "";
        try{//请求微信服务器，用code换取openid。HttpUtil是工具类，后面会给出实现，Configure类是小程序配置信息，后面会给出代码
            result = HttpUtil.doGet(
                    "https://api.weixin.qq.com/sns/jscode2session?appid="
                            + this.appID + "&secret="
                            + this.appSecret + "&js_code="
                            + code
                            + "&grant_type=authorization_code", null);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
//        ObjectMapper mapper = new ObjectMapper();
//        OpenIdJson openIdJson = mapper.readValue(result,OpenIdJson.class);
//        System.out.println(result.toString());
//        System.out.println(openIdJson.getOpenid());
//        return result;
        JSONObject jsonObject = JSONObject.fromObject(result);//解析从微信服务器上获取的json字符串
        System.out.println("用户的openid为: "+jsonObject.get("openid"));
        System.out.println("用户的session_key为: "+jsonObject.get("session_key"));


        map.put("session_key",jsonObject.get("session_key").toString());

        boolean count =wxService.selectByopenid(jsonObject.get("openid").toString());

        if(!count){
            //为false,则为第一次登陆,应将openid插入数据库中,再将openID和session_key放入缓存中,显示为正在登陆状态
            User user = new User();
            user.setOpenid(jsonObject.get("openid").toString());
            //TODO 将新用户保存进数据库
            wxService.insertUser(user);
            System.out.println("数据插入成功");
        }
        //count为true,表示查询有值,即为老用户,此时应将openID和session_key放入缓存中,显示为正在登陆状态
        //新来状态都应该将openidid和session_key 放入缓存中
        map.put("openid",jsonObject.get("openid").toString());
        return map;
    }

}
